// =====================================
// 作者：老曹  QQ:1484743
// 版权声明：本程序为个人原创、开源程序，禁止用于任何违法用途，任何违法用途均与作者无关。
// 仅限学习交流，转载请注明出处。如需商用请联系作者。
// =====================================
// main.js
$(function(){
    // 宿主机总览页
    if($('#host-overview').length){
        let allHosts = [];
        let pageSize = 20;
        let currentPage = 1;
        function renderPage(page) {
            $('#host-overview').empty();
            let start = (page-1)*pageSize;
            let end = start + pageSize;
            let hosts = allHosts.slice(start, end);
            let healthy=0, warning=0, danger=0;
            hosts.forEach(h=>{
                let diskHtml = '';
                if(h.disks && h.disks.length > 0){
                    h.disks.forEach((disk, idx)=>{
                        let color = disk.status === '健康' ? '#21ba45' : (disk.status === '预警' ? '#f2711c' : '#db2828');
                        let icon = disk.status === '健康' ? '✔️' : (disk.status === '预警' ? '⚠️' : '❌');
                        if(disk.status === '健康') healthy++;
                        else if(disk.status === '预警') warning++;
                        else danger++;
                        diskHtml += `<div style="margin-bottom:14px; padding-bottom:10px; border-bottom:1px dashed #eee;">
                            <div><b>硬盘:</b> <span style=\"color:${color};font-weight:bold;\">${icon} ${disk.device}</span></div>
                            <div><b>状态:</b> <span style=\"color:${color};font-weight:bold;\">${disk.status||'--'}</span></div>
                            <div><b>分数:</b> <b style=\"color:${color};font-size:1.1em;\">${disk.score||'--'}</b></div>
                        </div>`;
                    });
                }else{
                    diskHtml = '<div>无硬盘健康数据</div>';
                }
                // 判断离线状态
                let onlineHtml = '';
                if(h.last_report_time){
                    let last = new Date(h.last_report_time.replace(/-/g,'/')).getTime();
                    let now = Date.now();
                    if(now - last > 7*60*60*1000){
                        onlineHtml = '<span class="badge badge-danger ml-2">离线</span>';
                    }else{
                        onlineHtml = '<span class="badge badge-success ml-2">在线</span>';
                    }
                }else{
                    onlineHtml = '<span class="badge badge-danger ml-2">离线</span>';
                }
                $('#host-overview').append(
                    `<div class='col-md-3'>
                        <div class='card mb-2'>
                            <div class='card-body'>
                                <h5>${h.name||h.ip} ${onlineHtml}</h5>
                                ${diskHtml}
                            </div>
                        </div>
                    </div>`
                );
            });
            // 分页按钮
            let totalPages = Math.ceil(allHosts.length / pageSize);
            let pager = `<div class='w-100 text-center my-3'>`;
            if(page > 1) pager += `<button class='btn btn-sm btn-outline-primary mx-1' id='prev-page'>上一页</button>`;
            pager += `<span>第${page}/${totalPages}页</span>`;
            if(page < totalPages) pager += `<button class='btn btn-sm btn-outline-primary mx-1' id='next-page'>下一页</button>`;
            pager += `</div>`;
            $('#host-overview').append(pager);
            $('#prev-page').click(()=>{ currentPage--; renderPage(currentPage); });
            $('#next-page').click(()=>{ currentPage++; renderPage(currentPage); });
        }
        $.get('/api/host_list.php', function(data){
            allHosts = data;
            currentPage = 1;
            renderPage(currentPage);
            // 饼图统计所有主机所有硬盘健康分布
            let healthy=0, warning=0, danger=0;
            allHosts.forEach(h=>{
                if(h.disks && h.disks.length>0){
                    h.disks.forEach(disk=>{
                        if(disk.status==='健康') healthy++;
                        else if(disk.status==='预警') warning++;
                        else danger++;
                    });
                }
            });
            let chart = echarts.init(document.getElementById('health-pie'));
            chart.setOption({title:{text:'健康分布'},series:[{type:'pie',data:[{value:healthy,name:'健康'},{value:warning,name:'预警'},{value:danger,name:'危险'}]}]});
        });
    }
    // 宿主机详情页
    if($('#disk-list').length){
        let hostId = getQuery('hostId');
        $.get(`/api/health_status.php?hostId=${hostId}`, function(data){
            data.forEach(disk=>{
                $('#disk-list').append(`<div class='card mb-2'><div class='card-body'><h5>${disk.device} (${disk.model})</h5><p>序列号：${disk.serial}</p><p>分数：${disk.score}</p><p>状态：${disk.status}</p><p>异常：${disk.abnormal}</p></div></div>`);
            });
        });
    }
    // 预警中心
    if($('#warning-list').length){
        $.get('/api/warning/list', function(data){
            data.forEach(w=>{
                $('#warning-list').append(`<div class='alert alert-danger'>${w.time} ${w.host} ${w.disk} ${w.msg}</div>`);
            });
        });
    }
});
function getQuery(name){
    let reg = new RegExp('(^|&)'+name+'=([^&]*)(&|$)','i');
    let r = window.location.search.substr(1).match(reg);
    if(r!=null)return unescape(r[2]); return null;
} 